# -*- coding: utf-8 -*-
"""
   File Name : PutStorage
   Description :
   Author : Administrator
   date : 2024/6/2
   Change Activity : 2024/6/2:
"""
import json

from django.shortcuts import render
from django.views import View

from common.API import res_josn_data
from common.API.res_josn_data import fail_api, success_api
from common.filter.format import vague_filter
from common.layuiview.layuiviewsets import ModelViewSetLayui
from drf_auth_system.settings import admin_id
from product_drf.models import Product, PutStorage
from product_drf.serializers import ShipmentsQueryModelSerializer, PutStorageQueryModelSerializer, \
    PutStorageUpdateModelSerializer
from system_manage.models import Department


class PutStoragePage(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        departments = Department.objects.values('pk', 'name').all()
        return render(request, 'put_storage_manage/page.html', {'departments': departments})


class PutStorageGenericView(ModelViewSetLayui):
    queryset = PutStorage.objects.all()
    serializer_class = PutStorageQueryModelSerializer

    def create(self, request, *args, **kwargs):
        post_data = request.data.dict()
        product_obj = Product.objects.filter(pk=request.POST.get('fk_product')).first()
        if not product_obj:
            return fail_api(msg='产品不存在')
        req_quantity = int(post_data.get('quantity'))
        update_value = {
            'fk_product_to_put_storage_set': [{'quantity': product_obj.quantity + req_quantity}]
        }
        post_data.update(update_value)
        serializer = PutStorageUpdateModelSerializer(data=post_data)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return success_api('添加成功')

    def list(self, request, *args, **kwargs):
        page = request.GET.get('page', 1)
        limit = request.GET.get('limit', 10)
        post_data_str = request.GET.get('Params', None)
        print(request.GET)
        number = (int(page) - 1) * int(limit)  # 每页开始的序号
        if post_data_str is None:
            return res_josn_data.table_api(data=[])
        json_data = json.loads(post_data_str)

        fk_department = json_data.get('fk_department', None)
        try:
            json_data.pop('fk_department')
        except Exception:
            pass
        filters = vague_filter(json_data)  # 生成过滤器参数
        # 过滤库房和管理员
        if admin_id == request.session.get('role_id'):
            if fk_department:
                filters.update({'fk_department__exact': request.GET.get('fk_department', fk_department)})
        else:
            filters.update({'fk_department__exact': request.session.get('dept_id')})
        print('filters:', filters)
        queryset = self.get_serializer_class().Meta.model.objects.filter(**filters).order_by('-id')  # 过滤
        page = self.paginate_queryset(queryset)  # 分页
        serializer = self.get_serializer(queryset, many=True)  # 序列化

        if page is None:
            return res_josn_data.table_api(data=[])
        else:
            serializer_page = self.get_serializer(page, many=True)

            # print('返回数据:', serializer.data)
            return res_josn_data.table_api(count=len(serializer.data), data=serializer_page.data, number=number)


class PutStorageAdd(View):
    http_method_names = ['get']

    def get(self, request, *args, **kwargs):
        if admin_id == request.session.get('role_id'):
            departments = Department.objects.values('pk', 'name').all()
            products = Product.objects.values('pk', 'name')
        else:
            dept_id = request.session.get('dept_id')
            departments = Department.objects.filter(pk=dept_id).values('pk', 'name').all()
            products = Product.objects.filter(fk_department_id=dept_id).values('pk', 'name')
        return render(request, 'put_storage_manage/add.html', {'products': products, 'departments': departments})

